<?php

class IndexController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function indexAction() {
        $representation = new Db_Table_Representation();
        $representations = $representation->getNextRepresentation(4);
        $rowCount = count($representations);

        if (!$rowCount)
            $this->_forward('lastspectacles');

        $this->view->rowCount = $rowCount;
        $this->view->representations = $representations;

    }

    
    public function lastspectaclesAction() {
        $spectacle = new Db_Table_Spectacle();
        $spectacles = $spectacle->getLastSpectacles(4);
        $rowCount = count($spectacles);
        
        if ($rowCount)
            $this->render('default');
        
        $this->view->rowCount = $rowCount;
        $this->view->spectacles = $spectacles;        
    }
    
    
    public function reservationAction() {

        if (!$this->getRequest()->isPost()) {
            return $this->_forward('index');
        }

        $data['resa']['value'] = $_POST['resa'];
        $data['prenom']['value'] = trim((string) $_POST['prenom']);
        $data['nom']['value'] = trim((string) $_POST['nom']);
        $data['email']['value'] = trim(strtolower((string) $_POST['email']));
        $data['isModify'] = $isModify = (bool) $_POST['modify'];

        $data = $this->_validateForm($data);

        if ($data['has_errors']) {
            //Zend_Debug::dump($form);die;
            // Validation en echec
            $this->view->form = $form;
            return $this->render('form');
        }

        $values = $form->getValues();
    }

    private function _validateForm(array $data) {
        $validator = new Zend_Validate_Alpha(true);
        $data['has_errors'] = false;

        if (empty($data['prenom']['value']))
            $data['prenom']['errors'][] = 'Merci d\'indiquer votre prÃ©nom';
        elseif (strlen($data['prenom']['value']) < 3)
            $data['prenom']['errors'][] = 'Au moins 3 caractÃ¨res pour le prÃ©noms';
        elseif (!$validator->isValid($data['prenom']['value']))
            $data['prenom']['errors'][] = 'Ce champ n\'accepte pas de caractÃ¨res spÃ©ciaux';

        if (empty($data['nom']['value']))
            $data['nom']['errors'][] = 'Merci d\'indiquer votre nom';
        elseif (strlen($data['nom']['value']) < 3)
            $data['nom']['errors'][] = 'Au moins 3 caractÃ¨res pour le nom';
        elseif (!$validator->isValid($data['nom']['value']))
            $data['nom']['errors'][] = 'Ce champ n\'accepte pas de caractÃ¨res spÃ©ciaux';

        $validator = new Zend_Validate_EmailAddress();

        if (empty($data['email']['value']))
            $data['email']['errors'][] = 'Merci d\'indiquer votre email';
        elseif (!$validator->isValid($data['email']['value']))
            $data['email']['errors'][] = 'Votre email n\'est pas valide';

        $hasReserved = false;
        foreach ($data['resa']['value'] as $value)
            if ($value > 0)
                $hasReserved = true;

        if (!$hasReserved)
            $data['resa']['errors'] = 'Merci de sÃ©letionner une reprÃ©sentation';

        if(isset($data['prenom']['errors']) 
          || isset($data['nom']['errors'])
          || isset($data['email']['errors'])
          || (!$data['isModify'] && isset($data['resa']['errors'])))
        {
          
          $data['has_errors'] = true;
        }
        
        return $data;
    }

    /**
     *
     * @return Zend_Form 
     */
    private function _getReservationForm() {
        $form = new Zend_Form();
        //$form->setAction('/user/login')->setMethod('post');

        $firstname = $form->createElement('text', 'prenom');
        $firstname->addValidator('alnum')
                ->addValidator('regex', false, array('/^[a-z]+/'))
                ->addValidator('stringLength', false, array(2, 30))
                ->setRequired(true)
                ->addFilter('StringToLower')
                ->addFilter('StringTrim');

        $lastname = $form->createElement('text', 'nom');
        $lastname->addValidator('alnum')
                ->addValidator('regex', false, array('/^[a-z]+/'))
                ->addValidator('stringLength', false, array(2, 30))
                ->setRequired(true)
                ->addFilter('StringToLower')
                ->addFilter('StringTrim');

        $email = $form->createElement('text', 'email');
        $email->addValidator('emailAddress')
                ->setRequired(true)
                ->addFilter('StringToLower')
                ->addFilter('StringTrim');

        $form->addElement($firstname)
                ->addElement($lastname)
                ->addElement($email);

        return $form;

    }

    public function index2Action() {

        if ($this->isPost()) {

            $data['resa']['value'] = $_POST['resa'];
            $data['prenom']['value'] = trim((string) $_POST['prenom']);
            $data['nom']['value'] = trim((string) $_POST['nom']);
            $data['email']['value'] = trim((string) $_POST['email']);
            $isModify = (bool) $_POST['modify'];

            $data = $this->validateForm($data);

            // Si pas d'erreur dans le forme
            if (!isset($data['prenom']['errors'])
                    && !isset($data['nom']['errors'])
                    && !isset($data['email']['errors'])
                    && ($isModify || !isset($data['resa']['errors']))) {

                $this->saveReservation($data);
                $this->redirect('Reservation', 'List', array('email' => $data['email']['value']));
            }
        } elseif (isset($_GET['email'])) {

            require_once('model/Db/Spectateur.php');
            $spec = new Db_Spectateur();
            $spectateur = $spec->existSpectateur($_GET['email']);

            if ($spectateur) {
                $data['prenom']['value'] = $spectateur['prenom'];
                $data['nom']['value'] = $spectateur['nom'];
                $data['email']['value'] = $spectateur['email'];

                require_once('model/Db/Reserved.php');
                $reserveds = new Db_Reserved();
                $reserveds = $reserveds->getListOfReservation($spectateur['id_spectateur']);


                while ($reserved = $reserveds->fetch_assoc()) {
                    $data['resa']['value'][$reserved['id_spectacle_has_representation']]
                            = $reserved['number_seat'];
                    $data['resa']['seatavailable'][$reserved['id_spectacle_has_representation']]
                            = $reserved['number_seat'];
                }
            }
            $this->view->isModify = true;
        }


        require_once('model/Db/Spectacle.php');
        $spec = new Db_Spectacle();
        $this->view->spectacles = $spec->getListOfSpectacleHavingRepresentation();

        require_once('model/Db/Representation.php');
        $rep = new Db_Representation();
        $seatbookeds = $rep->getNumberOfSeatBooked();

        $maxseatavailable = 95;

        while ($seatbooked = $seatbookeds->fetch_assoc()) {
            $data['resa']['seatavailable'][$seatbooked['id_spectacle_has_representation']]
                    += $maxseatavailable - $seatbooked['number_seat_booked'];
        }

        $this->view->data = $data;
    }

}